package reflect.ioc;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Scanner;

public class MySpring {
    public Object getBean(String className){
        Object obj = null;
        Scanner scanner = new Scanner(System.in);

        try {
            Class clazz = null;
            //
            clazz = Class.forName(className);
            //创建对象
             obj = clazz.newInstance();
            //属性注入（DI）
            //1.通过clazz获取对象的所有私有属性-->获取属性的名字-->拼串构造set方法
            Field[] fields = clazz.getDeclaredFields();
            for (Field f : fields) {
                String name = f.getName();
                String firstLetter = name.substring(0, 1).toUpperCase();
                String otherLetter = name.substring(1);
                StringBuilder builder = new StringBuilder("set");
                builder.append(firstLetter);
                builder.append(otherLetter);
                Class filedType = f.getType();
                System.out.println(builder.toString());
                Method setMethod = clazz.getMethod(builder.toString(), filedType);
                System.out.println("请给属性" + name + "赋值");
                String value = scanner.nextLine();
                //如果是int等基本类型，需要把value进行转化为对应得类型

                if(filedType.getName().equals("int")){
                    setMethod.invoke(obj, Integer.parseInt(value));
                }


                //很重要的两行
                else {
                    Constructor con = filedType.getConstructor(String.class);
                    setMethod.invoke(obj, con.newInstance(value));
                }


            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;

    }
}
